package com.zlp.controller;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.util.UUID;

// https://www.imooc.com/article/309351
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("file")
public class FileController {

   private final RestTemplate restTemplate;


   /**
    *  restTemplate 上传文件
    *  访问地址: http://127.0.0.1:8110/file/uploadTest
    * @date: 2021/5/27 21:30
    * @return: java.lang.String
    */
   @GetMapping("uploadTest")
   public String uploadTest() {

      final String url = "http://127.0.0.1:8088/oss/file/uploadFile";
      MultiValueMap<String, Object> bodyParams = new LinkedMultiValueMap<>();
      String filePath = "D:\\file\\video\\test001.avi";
//      String filePath = "D:\\file\\oss\\001.jpg";
      // 封装请求参数
      FileSystemResource resource = new FileSystemResource(new File(filePath));
      bodyParams.add("file", resource);
      bodyParams.add("personId","p0001");
      bodyParams.add("reportNo","b0001");
      bodyParams.add("category",0);
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.MULTIPART_FORM_DATA);
      // heade 请求参数
      headers.add("Authorization", UUID.randomUUID().toString());
      HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyParams, headers);
      return  restTemplate.postForObject(url, requestEntity, String.class);
   }
}